package cn.zcy.condition;

import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.env.Environment;
import org.springframework.core.env.StandardEnvironment;
import org.springframework.core.type.AnnotatedTypeMetadata;

import java.util.Map;
import java.util.Set;

/**
 * 自定义bean的注册条件，windows操作系统注入
 */
public class WindowsCondition implements Condition {
    /**
     * 是否注册到IOC容器中的核心方法
     *
     * @param context
     * @param metadata
     * @return true的时候表示注册，否则，不注册
     */
    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        //1.获取ioc容器使用的beanFactory对象
        ConfigurableListableBeanFactory beanFactory = context.getBeanFactory();
        //2.获取类加载器
        ClassLoader classLoader = WindowsCondition.class.getClassLoader();

        //3.获取环境信息
        Environment environment = context.getEnvironment();
        //输出环境信息
        if (environment instanceof StandardEnvironment) {
            StandardEnvironment standardEnvironment = (StandardEnvironment) environment;
            Map<String, Object> map = standardEnvironment.getSystemProperties();
//            Set<Map.Entry<String, Object>> entries = map.entrySet();
            for (Map.Entry<String, Object> entries : map.entrySet()) {
                System.out.println(entries.getKey() + "==" + entries.getValue());
            }
        }
        //4.获取bean定义信息的注册器
        BeanDefinitionRegistry registry = context.getRegistry();
        //5.获取当前系统的名称
        String osName = environment.getProperty("os.name");
        //6.判断是否包含windows规则
        if (osName.contains("Windows")) {
            //需要注册到IOC
            return true;
        }
        //不需要注册到IOC容器中
        return false;
    }
}
